package com.wuhenzhizao.sku.widget;

import com.wuhenzhizao.sku.utils.ScreenUtils;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ScrollView;
import ohos.app.Context;


/**
 * Sku Item ScrollView
 * <p>
 * 解决Sku过多时，选择界面铺满全屏的问题
 * <p>
 * @author wuhenzhizao
 * @since 2017-08-02
 */
public class SkuMaxHeightScrollView extends ScrollView implements Component.EstimateSizeListener {

    /**
     * 构造
     *
     * @param context
     */
    public SkuMaxHeightScrollView(Context context) {
        this(context,null);
        setEstimateSizeListener(this);
        setMatchViewportEnabled(true);
    }

    /**
     * 构造
     *
     * @param context
     * @param attrs
     */
    public SkuMaxHeightScrollView(Context context, AttrSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        int width = EstimateSpec.getSize(widthMeasureSpec);
        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            Component child = getComponentAt(i);

            child.estimateSize(widthMeasureSpec, EstimateSpec.getSizeWithMode(0,EstimateSpec.UNCONSTRAINT));
            int h = child.getEstimatedHeight();
            if (h > height) {
                height = h;
            }
        }
        float heightDp = ScreenUtils.px2Dp(getContext(), height);
        if (heightDp > 220) {
            int maxHeight = ScreenUtils.dp2PxInt(getContext(), 220);
            setEstimatedSize(width, maxHeight);
        } else if (heightDp < 75) {
            int minHeight = ScreenUtils.dp2PxInt(getContext(), 75);
            setEstimatedSize(width, minHeight);
        } else {
//            super.onEstimateSize(widthMeasureSpec, heightMeasureSpec);
            return true;
        }
        return false;
    }
}
